import Request from "./requests";
import { mergeProps } from "../utils";
import { allLsGet } from "../utils/ls";

async function interceptorRequest(req) {
  const token = await allLsGet.global.token();
  const defaultHeader = {
    token,
  };
  req.headers = mergeProps(defaultHeader, req.headers);
  return req;
}

function interceptorResponse(response) {
  if (response.statusCode === 200) {
    return {
      result: response
    }
  }
  return {
    error: '下载出错',
  };
}

function errorHandler(error) {
  console.error(error);
  return {
    error,
  };
}

function request(requestConfig = {}, config) {
  const instance = new Request({
    timeout: 60 * 1000,
    baseURL: process.env.VUE_APP_BASE_API,
    responseType: 'blob',
    ...requestConfig
  });
  instance.interceptorsRequest(interceptorRequest, errorHandler);
  instance.interceptorsResponse(interceptorResponse, errorHandler);
  return instance.send(config);
}

export default request;
